﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Threading;

namespace ExecutionContextStudy
{
    class CancellationTest
    {
        public static void Test()
        {
            CancellationTokenSource cts = new CancellationTokenSource();

            cts.Token.Register(() =>
            {
                Console.WriteLine("Cancel callback 1，In Thread：" + Thread.CurrentThread.ManagedThreadId);
            });
            cts.Token.Register(() =>
            {
                Console.WriteLine("Cancel callback 2，In Thread：" + Thread.CurrentThread.ManagedThreadId);
            }, true);


            ThreadPool.QueueUserWorkItem(o => Count(cts.Token, 10));
            Console.WriteLine("Press <Enter> to cancel the operation.");
            Console.ReadLine();

            cts.CancelAfter(500);

            cts.Token.Register(() =>
            {
                Console.WriteLine("Cancel callback 3，In Thread：" + Thread.CurrentThread.ManagedThreadId);
            });
            cts.Token.Register(() =>
            {
                Console.WriteLine("Cancel callback 4，In Thread：" + Thread.CurrentThread.ManagedThreadId);
            }, true);
            Console.ReadLine();
        }

        private static void Count(CancellationToken token, Int32 countTo)
        {
            for (Int32 count = 0; count < countTo; count++)
            {
                if (token.IsCancellationRequested)
                {
                    Console.WriteLine("Count is cancelled，In Thread：" + Thread.CurrentThread.ManagedThreadId);
                    break;
                }
                Console.WriteLine(count);
                Thread.Sleep(200);
            }
            Console.WriteLine("Count is done，In Thread：" + Thread.CurrentThread.ManagedThreadId);
        }
    }
}
